﻿using System;
using System.Collections.Generic;
using System.Linq;
using SQLStore;
using System.Data.Entity.Migrations;
using System.Linq.Expressions;
using Models;

namespace Services
{
    public class TagServices : IDataAccess<Tag>
    {
        CMSDBContext db ;

        public TagServices()
        {
            db = new CMSDBContext();
        }
        public TagServices(string connectionString)
        {
            db = new CMSDBContext(connectionString);
        }
        public int Delete(object objValue)
        {
            Guid tagId = Guid.Parse(objValue.ToString());
            var entity = db.Set<Tag>().Where(t => t.TagId == tagId).FirstOrDefault();
            if (entity != null)
            {
                db.Set<Tag>().Remove(entity);
            }
            return Save();
        }

        public bool Exists(Expression<Func<Tag, bool>> exp)
        {
            return db.Set<Tag>().Any(exp);
        }

        public bool Exists(object objValue)
        {
            string tagName = objValue.ToString();
            return db.Set<Tag>().Any(t => t.TagName == tagName);
        }

        public Tag GetByID(object objValue)
        {
            Guid tagId = Guid.Parse(objValue.ToString());
            return db.Set<Tag>().Where(t => t.TagId == tagId).FirstOrDefault();
        }

        public Tag GetByName(string name)
        {
            return db.Set<Tag>().Where(t => t.TagName == name).FirstOrDefault();
        }
        public Tag GetByUrl(string tagUrl)
        {
            return db.Set<Tag>().Where(t => t.TagUrl == tagUrl).FirstOrDefault();
        }


        public List<Tag> GetList(Expression<Func<Tag, bool>> exp)
        {
            return db.Set<Tag>().Where(exp).OrderBy(t => t.Sort).ToList();
        }

        public int Save(Tag entity)
        {
            db.Set<Tag>().AddOrUpdate(entity);
            return Save();
        }

        int Save()
        {
            return db.SaveChanges();
        }

    }
}